import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';

import '../../../../core/model/pgc_page_bangumi_model.dart';
import '../../../../core/service/request/pgc_page_bangumi_request.dart';
import '../../../shared/color_radix_change.dart';
import '../../../shared/platform_judge.dart';
import '../../../widgets/rank_no.dart';

///番剧排名排名1,2,3...的背景颜色
List<Color> _rankColor = [
  const Color.fromRGBO(252, 176, 38, 1),
  const Color.fromRGBO(147, 176, 219, 1),
  const Color.fromRGBO(236, 158, 145, 1),
  const Color.fromRGBO(122, 134, 150, .9),
  const Color.fromRGBO(122, 134, 150, .8),
  const Color.fromRGBO(122, 134, 150, .7),
  const Color.fromRGBO(122, 134, 150, .6),
  const Color.fromRGBO(122, 134, 150, .5),
  const Color.fromRGBO(122, 134, 150, .5),
  const Color.fromRGBO(122, 134, 150, .5),
];

class HYHomeComicScreen extends StatefulWidget {
  const HYHomeComicScreen({Key? key}) : super(key: key);

  @override
  State<HYHomeComicScreen> createState() => _HYHomeComicScreenState();
}

class _HYHomeComicScreenState extends State<HYHomeComicScreen>
    with AutomaticKeepAliveClientMixin {
  late final List<Module> _modules = [];
  late final List<Module> _modulesList00 = [];
  late final List<Module> _modulesList01 = [];
  late final List<Module> _modulesList02 = [];
  late ScrollController _easyRefreshScrollController;
  late ScrollController _customScrollController;
  late ScrollController _buttonsScrollController;
  late SwiperController _swiperController;
  List<Widget> widgets = [];

  @override
  void initState() {
    _customScrollController = ScrollController();
    _easyRefreshScrollController = ScrollController();
    _buttonsScrollController = ScrollController();
    _swiperController = SwiperController();

    ///获取动画的json数据
    HYGrcPageBangumiRequest.getPageBangumiData().then((value) {
      _modules.addAll(value.modules);
      _modulesList00.addAll(value.modules.getRange(2, 3));
      _modulesList01.addAll(value.modules.getRange(3, 8));
      _modulesList02.addAll(value.modules.getRange(9, 14));

      ///动态添加
      widgets.addAll([
        buildHomeComicSwiper(),
        10.verticalSpace,
        buildHomeComicFunctionButton(),
        10.verticalSpace,
        buildDoubleFeedZone(_modulesList00),
        20.verticalSpace,
        BuildBangumiRankZone(8, _modules),
        buildDoubleFeedZone(_modulesList01),
        20.verticalSpace,
        BuildBangumiRankZone(14, _modules),
        buildDoubleFeedZone(_modulesList02),
      ]);
      Timer(const Duration(seconds: 3), () {
        if (mounted) setState(() {});
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _easyRefreshScrollController.dispose();
    _buttonsScrollController.dispose();
    _swiperController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: widgets.isNotEmpty
          ? Container(
              padding: const EdgeInsets.only(left: 10, right: 10, top: 10).r,
              child: EasyRefresh(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: widgets,
                ),
              ),
            )
          : Container(
              margin: EdgeInsets.only(top: 30.h),
              alignment: Alignment.topCenter,
              width: 1.sw,
              child: const RefreshProgressIndicator(
                value: null,
                color: HYAppTheme.norMainThemeColors,
              ),
            ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  ///广告栏
  Widget buildHomeComicSwiper() {
    return _modules.isNotEmpty
        ? SizedBox(
      height: 240.h,
            child: Swiper(
              scale: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
              viewportFraction: PlatformJudge.platformJudgeIsPhone() ? 1 : .7,
              autoplay: true,
              autoplayDelay: 3000,
              controller: _swiperController,
              pagination: SwiperPagination(
                alignment: Alignment.bottomCenter,
                builder: SwiperCustomPagination(
                  builder: (ctx, config) {
                    return BangumiSwiperPagination(
                        currentIndex: config.activeIndex,
                        itemCount: _modules[0].items.length);
                  },
                ),
              ),
              itemBuilder: (ctx, index) {
                return Container(
                  margin: const EdgeInsets.only(bottom: 30).r,
                  height: 260.h,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                        image: NetworkImage(
                          _modules[0].items[index].cover!,
                        ),
                        fit: BoxFit.fill,
                        filterQuality: FilterQuality.low,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(8.r))),
                );
              },
              itemCount: _modules[0].items.length,
            ),
          )
        : Container();
  }

  ///功能按钮
  Widget buildHomeComicFunctionButton() {
    return _modules.isNotEmpty
        ? Container(
            width: .9.sw,
            height: 80.h,
            alignment: Alignment.center,
            child: ListView.builder(
              shrinkWrap: true,
              controller: _buttonsScrollController,
              scrollDirection: Axis.horizontal,
              itemBuilder: (ctx, index) {
                return Container(
                  padding: const EdgeInsets.only(right: 20).r,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        width: 35.r,
                        height: 35.r,
                        child: FadeInImage(
                          placeholder: AssetImage(
                            ImageAssets.icUpperVideoDefaultPNG,
                          ),
                          image: NetworkImage(
                            _modules[1].items[index].cover!,
                          ),
                          fit: BoxFit.fill,
                          placeholderFit: BoxFit.fill,
                        ),
                      ),
                      10.verticalSpace,
                      Text(
                        _modules[1].items[index].title,
                        style: TextStyle(
                          color: HYAppTheme.norTextColors,
                          fontSize: HYAppTheme.xxxSmallFontSize,
                        ),
                      ),
                    ],
                  ),
                );
              },
              itemCount: _modules[1].items.length,
            ),
          )
        : Container();
  }

  ///固定每一个块的大小，一行能排几个就几个
  Widget buildDoubleFeedZone(List<Module> modulesList) {
    List<Item> _items = [];
    for (var module in modulesList) {
      _items.addAll(module.items);
    }
    return modulesList.isNotEmpty
        ? CustomScrollView(
            controller: _customScrollController,
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            slivers: [
              SliverGrid(
                delegate: SliverChildBuilderDelegate(
                  (ctx, index) {
                    return SizedBox(
                      width: 180.w,
                      height: 200.h,
                      child: Card(
                        elevation: .3,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Stack(
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image:
                                            NetworkImage(_items[index].cover!),
                                        fit: BoxFit.fill,
                                        filterQuality: FilterQuality.low),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(5.r),
                                    ),
                                  ),
                                  width: 180.w,
                                  height: 110.h,
                                ),
                                Positioned(
                                  child: Container(
                                    width: 180.w,
                                    height: 40.h,
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        colors: [
                                          HYAppTheme.norTextColors
                                              .withOpacity(.7),
                                          Colors.transparent,
                                        ],
                                        begin: Alignment.bottomCenter,
                                        end: Alignment.topCenter,
                                      ),
                                    ),
                                    padding:
                                        const EdgeInsets.only(right: 8, left: 8)
                                            .r,
                                    child: Row(
                                      children: [
                                        Text(
                                          _items[index].bottomLeftBadge!.text,
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize:
                                                HYAppTheme.xxxSmallFontSize,
                                          ),
                                        ),
                                        Text(
                                          _items[index].stat!.followView,
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize:
                                                HYAppTheme.xxxSmallFontSize,
                                          ),
                                        ),
                                      ],
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                    ),
                                  ),
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                ),
                                _items[index].badgeInfo != null
                                    ? Positioned(
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color: ColorRadixChange.hexColor(
                                                _items[index]
                                                    .badgeInfo!
                                                    .bgColor!
                                                    .substring(1)),
                                            borderRadius:
                                                BorderRadius.horizontal(
                                              left: Radius.circular(8.r),
                                            ),
                                          ),
                                          child: Text(
                                            _items[index].badgeInfo!.text!,
                                            style: TextStyle(
                                              fontSize:
                                                  HYAppTheme.xxxSmallFontSize,
                                              color: Colors.white,
                                            ),
                                          ),
                                          padding: const EdgeInsets.only(
                                            left: 5,
                                            right: 3,
                                            top: 2,
                                            bottom: 4,
                                          ).r,
                                        ),
                                        right: 0.w,
                                        top: 10.h,
                                      )
                                    : Container()
                              ],
                            ),
                            5.verticalSpace,
                            Container(
                              child: Text(
                                _items[index].title,
                                style: TextStyle(
                                  color: HYAppTheme.norTextColors,
                                  fontSize: HYAppTheme.xxSmallFontSize,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              alignment: Alignment.centerLeft,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 10).r,
                            ),
                            5.verticalSpace,
                            Container(
                              padding: const EdgeInsets.only(left: 10).r,
                              child: Container(
                                child: Text(
                                  _items[index].subTitleLeftBadge == null
                                      ? "0.0"
                                      : _items[index].subTitleLeftBadge!.text,
                                  style: TextStyle(
                                    color:
                                        const Color.fromRGBO(241, 129, 56, 1),
                                    fontSize: HYAppTheme.xxSmallFontSize,
                                  ),
                                ),
                                padding: const EdgeInsets.all(2).r,
                                decoration: BoxDecoration(
                                    color: HYAppTheme.norWhite05Color,
                                    borderRadius: BorderRadius.all(
                                      const Radius.circular(2).r,
                                    )),
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  childCount: _items.length,
                ),
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                  mainAxisExtent: 200.h,
                  maxCrossAxisExtent:
                      PlatformJudge.platformJudgeIsPhone() ? 180.w : 100.w,
                ),
              ),
            ],
          )
        : Container();
  }
}

///热门番剧区、热门国创区
class BuildBangumiRankZone extends StatefulWidget {
  int zoneNum;
  List<Module> modules;

  BuildBangumiRankZone(this.zoneNum, this.modules);

  @override
  State<BuildBangumiRankZone> createState() => _BuildBangumiRankZoneState();
}

class _BuildBangumiRankZoneState extends State<BuildBangumiRankZone> {
  late ScrollController _rankScrollController;

  @override
  void initState() {
    _rankScrollController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _rankScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<Module> _modules = widget.modules;
    int _zoneNum = widget.zoneNum;
    return _modules.isNotEmpty
        ? Column(
            children: [
              Stack(
                children: [
                  Card(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadiusDirectional.circular(10.r)),
                    clipBehavior: Clip.antiAlias,
                    child: Opacity(
                      opacity: .3,
                      child: Container(
                        color: HYAppTheme.norTextColors,
                        child: Image.network(
                          _modules[_zoneNum].cover!,
                          fit: BoxFit.fill,
                          height: 360.h,
                          width: 1.sw,
                        ),
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(10).r,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              _modules[_zoneNum].title!,
                              style: TextStyle(
                                color: HYAppTheme.norTextColors,
                                fontSize: HYAppTheme.normalFontSize,
                              ),
                            ),
                            Text(
                              _modules[_zoneNum].headers![0].title + ">",
                              style: TextStyle(
                                color: HYAppTheme.norTextColors,
                                fontSize: HYAppTheme.xxSmallFontSize,
                              ),
                            ),
                          ],
                        ),
                        Text(
                          _modules[_zoneNum].desc!,
                          style: TextStyle(
                            color: HYAppTheme.norGrayColor,
                            fontSize: HYAppTheme.xxSmallFontSize,
                          ),
                        ),
                        SizedBox(
                          height: 350.h,
                          child: ListView.builder(
                            controller: _rankScrollController,
                            scrollDirection: Axis.horizontal,
                            shrinkWrap: true,
                            // physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (ctx, index) {
                              return Container(
                                padding:
                                    const EdgeInsets.only(top: 10, right: 5).r,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Stack(
                                      children: [
                                        Container(
                                          height: 230.h,
                                          width: 80.w,
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(5.r)),
                                              image: DecorationImage(
                                                  image: NetworkImage(
                                                      _modules[_zoneNum]
                                                          .items[index]
                                                          .cover!),
                                                  fit: BoxFit.cover,
                                                  filterQuality:
                                                      FilterQuality.low)),
                                        ),
                                        Positioned(
                                          child: HYRankNo(
                                            text: (index + 1).toString(),
                                            color: _rankColor[index],
                                          ),
                                          left: 0,
                                          top: 0,
                                        ),
                                        Positioned(
                                          child: Text(
                                            _modules[_zoneNum]
                                                .items[index]
                                                .bottomRightBadge!
                                                .text,
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize:
                                                  HYAppTheme.xxxSmallFontSize,
                                            ),
                                          ),
                                          right: 5.w,
                                          bottom: 5.h,
                                        ),
                                      ],
                                    ),
                                    Container(
                                      padding: const EdgeInsets.only(top: 5).r,
                                      alignment: Alignment.centerLeft,
                                      width: 80.w,
                                      child: Text(
                                        _modules[_zoneNum].items[index].title,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          color: HYAppTheme.norTextColors,
                                          fontSize: HYAppTheme.xxSmallFontSize,
                                        ),
                                      ),
                                    ),
                                    Container(
                                      padding: const EdgeInsets.only(top: 5).r,
                                      alignment: Alignment.centerLeft,
                                      width: 80.w,
                                      child: Text(
                                        _modules[_zoneNum].items[index].desc!,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          color: HYAppTheme.norGrayColor,
                                          fontSize: HYAppTheme.xxSmallFontSize,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                            itemCount: 10,
                            // itemCount: _modules[zoneNum].items.length,
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ],
          )
        : Container();
  }
}

///轮播图的底部的指示标志
class BangumiSwiperPagination extends StatefulWidget {
  ///当前的页面的下标
  int currentIndex;

  ///总共几个页面
  int itemCount;

  BangumiSwiperPagination(
      {Key? key, required this.currentIndex, required this.itemCount})
      : super(key: key);

  @override
  State<BangumiSwiperPagination> createState() =>
      _BangumiSwiperPaginationState();
}

class _BangumiSwiperPaginationState extends State<BangumiSwiperPagination> {
  late ScrollController _swiperPaginationController;

  @override
  void initState() {
    _swiperPaginationController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _swiperPaginationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 70.w,
      child: GridView.builder(
        controller: _swiperPaginationController,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: widget.itemCount,
          childAspectRatio: 5 / 2,
        ),
        itemBuilder: (BuildContext context, int index) {
          return widget.currentIndex == index
              ? Container(
                  decoration: BoxDecoration(
                      color: HYAppTheme.norMainThemeColors,
                      borderRadius: BorderRadius.circular(5.r)),
                )
              : CircleAvatar(
                  backgroundColor: HYAppTheme.norGrayColor,
                  radius: 4.r,
                );
        },
        itemCount: widget.itemCount,
      ),
    );
  }
}
